/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.home.Common;

import java.util.Random;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

import org.apache.commons.codec.binary.Base64;

/**
 *
 * @author DUYPHAN
 */
public class PasswordBasedEncryption {

    private static int ITERATORS = 1000;

    public static String encrypt(String str,String pass)
    {
        String result = "";
        byte[] salt = new byte[8];
        Random rd = new Random();
        rd.nextBytes(salt);

        PBEParameterSpec paramSpec = new PBEParameterSpec(salt, ITERATORS);
        PBEKeySpec keySpec = new PBEKeySpec(pass.toCharArray());

        try {
            SecretKeyFactory keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
            SecretKey key = keyFac.generateSecret(keySpec);

            Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
            cipher.init(Cipher.ENCRYPT_MODE,key, paramSpec);

            byte[] cipherText = cipher.doFinal(str.getBytes());

            //BASE64Encoder encoder = new BASE64Encoder();
            byte[] strSalt = Base64.encodeBase64(salt);
            byte[] strCipher = Base64.encodeBase64(cipherText);

            result = new String(strSalt) + new String(strCipher);
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return result;
    }

    public static String decrypt(String str,String pass)
    {
        String result = "";

        String salt = str.substring(0,12);
        String decryptStr = str.substring(12,str.length());

        //BASE64Decoder decoder = new BASE64Decoder();

        try {
            byte[] saltArray = Base64.decodeBase64(salt);
            byte[] decryptStrArray = Base64.decodeBase64(decryptStr);

            PBEKeySpec keySpec = new PBEKeySpec(pass.toCharArray());
            SecretKeyFactory keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
            SecretKey key = keyFac.generateSecret(keySpec);

            PBEParameterSpec paramSpec = new PBEParameterSpec(saltArray, ITERATORS);

            Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
            cipher.init(Cipher.DECRYPT_MODE, key,paramSpec);

            byte[] plaintextArray = cipher.doFinal(decryptStrArray);

            result = new String(plaintextArray);
        } catch (Exception e) {
        }

        return result;
    }

}
